package gs.android.calcfeud;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class GameModel {
	private GamePersistor persistor;
	
	private Field[] fields;
	private Player home, away;
	private Button roll;
	private Dice dice;
	
	public GameModel(GamePersistor persistor) {
		this.persistor = persistor;
		
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inScaled = false;
		
		fields = new Field[100];
		fields[0] = new Field(0f, 0f, 10f, 16.667f, 1);
		spiral(1, 1, 0, 0);
		
		// button
		Bitmap bitmap = BitmapFactory.decodeResource(this.persistor.getResources(), R.drawable.button_unclicked, options);
		float width = 50;
		float height = 6;
		float x = (GamePersistor.SCREEN_WIDTH / 2) - (GamePersistor.SCREEN_WIDTH / 100f * width / 2);
		float y = GamePersistor.SCREEN_HEIGHT - ((((GamePersistor.SCREEN_HEIGHT / 2) - (GamePersistor.SCREEN_WIDTH / 2)) / 2) + (GamePersistor.SCREEN_HEIGHT / 100f * height / 2));
		roll = new Button(x, y, height, width, false, "Roll", bitmap);
		
		// dice
		Bitmap dicesheet = BitmapFactory.decodeResource(persistor.getResources(), R.drawable.dicesheet, options);
		width = 20f;
		height = 12f;
		x = (GamePersistor.SCREEN_WIDTH / 2) - (GamePersistor.SCREEN_WIDTH / 100f * width / 2);
		y = (((GamePersistor.SCREEN_HEIGHT / 2) - (GamePersistor.SCREEN_WIDTH / 2)) / 2) - (GamePersistor.SCREEN_HEIGHT / 100f * height / 2);
		dice = new Dice(x, y, height, width, 6, dicesheet);
		
		// player home
		Bitmap player_home = BitmapFactory.decodeResource(persistor.getResources(), R.drawable.player_home, options);
		home = new Player(0f, 0f, GamePersistor.SCREEN_WIDTH / 10, GamePersistor.SCREEN_WIDTH / 10, player_home, this);
		
		// player away
		Bitmap player_away = BitmapFactory.decodeResource(persistor.getResources(), R.drawable.player_away, options);
		away = new Player(0f, 0f, GamePersistor.SCREEN_WIDTH / 10, GamePersistor.SCREEN_WIDTH / 10, player_away, this);
	}
	
	public void onPause() {
		
	}
	
	public void onResume() {
		
	}
    
    public void spiral(int n, int steps, int x, int y) {
    	int dx = (n % 2 == 1 ? 2 - (n % 4) : 0);
    	int dy = (n % 2 == 0 ? 1 - (n % 4) : 0);
    	int length = (n + 1) / 2;
    	
    	for (int i = 1; i < length + 1; i++)
    		if (steps + i < 101)
    			fields[steps + i - 1] = new Field(x + (dx * i), y + (dy * i), 10f, 16.667f, steps + i);
    	
    	if (steps + length < 101)
    		spiral(n + 1, steps + length, x + (dx * length), y + (dy * length));
    }
    
    public Field[] getFields() {
    	return fields;
    }
    
    public Button getButton() {
    	return roll;
    }
    
    public Dice getDice() {
    	return dice;
    }
    
    public Player getHome() {
    	return home;
    }
    
    public Player getAway() {
    	return away;
    }
}
